/**
 * Created by Administrator on 15-6-19.
 */
var queryOTtimeByMonth = function(month){
	$("#calendarContent").find(".detail").removeClass("valid");
	PFT.Ajax({
		url : "call/route_Calendar_Ajax.php",
		type : "get",
		dataType : "json",
		data : {
			orderMonth : month,
			pid : $("#pid").val(),
			aid : $("#aid").val()
		}
	},function(res){
		var valids = res.pricelists;
		for(var i=0,len=valids.length; i<len; i++){
			var valid = valids[i];
			var date = valid["date"];
			var price = valid["price"];
			$("#calendar-day-"+date).addClass("valid").addClass("enable").append(
				'<span class="price"><i class="yen">&yen;</i><span class="num">'+price+'</span></span>'
			);
		}
	})
};
var Calendar = RichBase.extend({
	statics : {},
	EVENTS : {
		"click" : {
			".close" : "onCloseClick",
			".title .lastmonth" : "onPrevmonthClick",
			".title .nextmonth" : "onNextmonthClick",
			".detail" : "onDateSelect"
		}
	},
	init : function(opt){
		this.container = opt.container;

	},
	onCloseClick : function(that,e){
		that.close(null);
	},
	onDateSelect : function(that,e){
		var tarDateBox = $(e.currentTarget);
		var currentDate = that.currentDate;
		if(currentDate.length==10) currentDate = currentDate.substring(0,7);
		var tarDate = tarDateBox.find(".dateNum").text();
		tarDate = currentDate+"-"+tarDate;
		that.fire("onSelect",tarDate);
		if(tarDateBox.hasClass("valid")){
			that.fire("onValidSelect",tarDate);
			that.close(tarDate);
		}else{
			that.fire("onUnvalidSelect",tarDate);
		}
	},
	onNextmonthClick : function(that,e){
		var nextmonth = CalendarCore.nextMonth(that.currentDate);
		that.show(nextmonth);
		queryOTtimeByMonth(nextmonth);
	},
	onPrevmonthClick : function(that,e){
		var prevmonth = CalendarCore.prevMonth(that.currentDate);
		that.show(prevmonth);
		queryOTtimeByMonth(prevmonth);
	},
	show : function(date){
		date = date || CalendarCore.gettoday();
		this.container.show().html(CalendarCore.outputHtml(date));
		this.currentDate = date;
	},
	close : function(date){
		this.container.hide();
		this.fire("onClose",date);
	}
});
//场次列表
var ChangciList = RichBase.extend({
	statics : {},
	EVENTS : {
		"click" : {
			"#changciUl .changciItem" : "onChangciClick"
		}
	},
	init : function(opt){
		var that = this;
		this.container = $("#changciListWrap");
		this.listUl = $("#changciUl");
		this.changciInp = $("#selectchangciInput");
		this.container.click(function(){ that.hide()});
	},
	abort : function(){ this.xhr && this.xhr.abort() },
	show : function(){
		var inp = this.changciInp;
		var offset = inp.offset();
		this.container.show().children().css({
			left : offset.left,
			top : offset.top + inp.innerHeight() + 2
		})
	},
	hide : function(){
		this.container.hide();
	},
	query : function(date){
		var that = this;
		var lid = $("#gLidHidInp").val();
		var venueId = $("#venueIdHidInp").val();
		if(!date) return false;
		this.abort();
		this.xhr = PFT.Ajax({
			url : "call/before_ph_data.php",
			type : "GET",
			dataType : "json",
			data : {
				m : "round",
				date : date,
				venus_id : venueId
			},
			loading : function(){
				that.listUl.html('<li class="loading" style="height:200px; width:383px; line-height:200px; text-align:center;">正在加载...</li>');
			},
			removeLoading : function(){ that.listUl.html()},
			timeout : function(){ alert("网络请求超时，请稍后重试")},
			serverError : function(){ alert("网络请求出错，请稍后重试")}
		},function(res){
			var list = [];
			if(res.status=="success"){
				for(var i in res.rounds){
					var d = {};
					var r = res.rounds[i];
					var area_storage = r["area_storage"];
					var storageArr = [];
					for(var i in area_storage){
						storageArr.push(i+","+area_storage[i]);
					}
					d["id"] = r["id"];
					d["title"] = r["round_name"];
					d["begintime"] = r["bt"];
					d["endtime"] = r["et"];
					d["storage"] = r["storage"];
					d["area_storage"] = storageArr.join("|");
					list.push(d);
				}
			}else{
				alert(res.msg || "查询场次信息出错，请稍后重试");
			}
			var html = that.buildHtml(list);
			that.listUl.html(html);
			setTimeout(function(){
				if(res.rounds.length){
					that.listUl.children().first().trigger("click");
				}else{
					that.changciInp.val("该日期没有场次安排");
					$("#proTable").find(".countInp").val(0).attr("readonly",true);
				}
			},10)
		})
	},
	buildHtml : function(data){
		var that = this;
		var tpl = $("#changciListTpl").html();
		var html = "";
		for(var i in data){
			var changci = data[i];
			html += that.parseTemplate(tpl,changci);
		}
		return html
	},
	onChangciClick : function(that,e){
		var tarLi = $(e.currentTarget);
		var time = tarLi.attr("data-time");
		var area_storage = tarLi.attr("data-areastorage");
		var roundId = tarLi.attr("data-id");
		if(tarLi.hasClass("active")) return false;
		that.hide();
		tarLi.addClass("active").siblings().removeClass("active");
		$("#roundIdHidInp").val(roundId)
		that.fire("changciChange",time,area_storage);
	}
});
//产品列表
var Product = RichBase.extend({
	statics : {},
	EVENTS : {
		"focus" : {
			".formInp" : "onInputFocus"
		},
		"blur" : {
			".formInp" : "onInputBlur"
		},
		"click" : {
			".coutTd .countBtn" : "onCountBtnClick"
		}
	},
	init : function(opt){ },
	onInputFocus : function(that,e){
		var tarInp = $(e.currentTarget);
		tarInp.attr("data-orign",tarInp.val());
	},
	onInputBlur : function(that,e){
		var tarInp = $(e.currentTarget);
		var areaid = tarInp.attr("data-areaid");
		var storage = tarInp.attr("data-storage");
		var orignVal = tarInp.attr("data-orign");
		var val = tarInp.val();
		if(!val || !PFT_GLOBAL.U.isPositiveNum(val)){
			tarInp.val(orignVal);
			return false;
		}
		that.changeCount(tarInp,areaid,storage,orignVal,val);
	},
	onCountBtnClick : function(that,e){
		var tarBtn = $(e.currentTarget);
		var tarInp = tarBtn.siblings(".formInp");
		var val = tarInp.val(), newVal=0;
		var storage = tarInp.attr("data-storage");
		var areaid = tarInp.attr("data-areaid");
		if(tarBtn.hasClass("disable")) return false;
		if(tarBtn.hasClass("plus")){
			newVal = Number(val)+1;
		}else{
			newVal = Number(val)-1;
		}
		that.changeCount(tarInp,areaid,storage,val,newVal);
	},
	//改变票数，增减或手动输入
	changeCount : function(tarInp,areaid,storage,orignCount,newCount){
		if(!storage) storage = 0;
		if(!tarInp || typeof newCount=="undefined" || typeof newCount=="undefined") return false;
		storage = Number(storage);
		newCount = Number(newCount);
		tarInp.val(newCount);
		if(storage==0 && areaid==0){
			storage = 10000;
		}else{
//			return false;
		}
		var minuBtn = tarInp.siblings(".sub");
		var addBtn = tarInp.siblings(".plus");
		var tprice = Number(tarInp.attr("data-tprice"));
		var inps = $("#proTable").find(".countInp_"+areaid);
		var totalCount = (function(){
			var totalCount = 0;
			inps.each(function(){
				totalCount += Number($(this).val());
			})
			return totalCount;
		})();
		var totalMoney = 0;
		var totalTicket = 0;
		if(totalCount>storage){
			alert("分区库存数量不足");
			tarInp.val(orignCount);
			return false;
		}
		if(newCount==0){
			minuBtn.addClass("disable");
			addBtn.removeClass("disable");
			tarInp.val(newCount);
		}else if(totalCount==storage){
			$("#proTable").find(".plus_"+areaid).addClass("disable");
			minuBtn.removeClass("disable");
			tarInp.val(newCount);
		}else{
			$("#proTable").find(".countInp_"+areaid).each(function(){
				var tarInp = $(this);
				var minuBtn = tarInp.siblings(".sub");
				var addBtn = tarInp.siblings(".plus");
				addBtn.removeClass("disable");
				if(tarInp.val()!="0"){
					minuBtn.removeClass("disable");
				}else{
					minuBtn.addClass("disable");
				}
			})
		}
		tarInp.parent().next().find(".num").text(tprice*newCount);
		$("#proTable").find(".smallTotalNum").each(function(){
			totalMoney += Number($(this).text());
		});
		$("#proTable").find(".formInp").each(function(){
			totalTicket += Number($(this).val());
		});
		$("#summoney").text(totalMoney);
		$("#sumtnum").text(totalTicket);
		this.fire("countChanged",orignCount,newCount);
	},
	//根据场次更改库存
	changeStorage : function(data){
		if(!data) return false;
		data = data.split("|");
		for(var i in data){
			var d = data[i];
			var arr = d.split(",");
			var storage = arr[1];
			var tarCountInp = $("#proTable").find(".countInp_"+arr[0]);
			$("#storage_td_"+arr[0]).text(storage);
			tarCountInp.attr("data-storage",storage);
			tarCountInp.removeAttr("readonly");
			if(Number(storage)>0){
				tarCountInp.siblings(".plusBtn").removeClass("disable");
			}
		}
	}
});
//main
var Order = RichBase.extend({
	statics : {},
	EVENTS : {
		"click" : {
			"#selectDateTrigger" : "onSelectDateInputClick",
			"#selectDateInput" : "onSelectDateInputClick",
			"#selectChangciTrigger" : "selectChangciTrigger",
			"#selectchangciInput" : "selectChangciTrigger"
		}
	},
	init : function(opt){
		this.container = opt.container;
		this.dateInp = $("#selectDateInput");
		this.changciInp = $("#selectchangciInput");
		this.calendar = this.importCalendar();
		this.changeciList = this.importChangciList();
		this.product = this.importProduct();
		var defaulttime = this.dateInp.val();
		defaulttime && this.changeciList.query(defaulttime);
	},
	//载入日历模块
	importCalendar : function(){
		var that = this;
		var proTable = $("#proTable")
		return new Calendar({container:$("#calendarWrap")}).on("onValidSelect",function(date){
			$("#sumtnum").text(0);
			$("#summoney").text(0);
			proTable.find(".countInp").val(0);
			proTable.find(".plusBtn").addClass("disable");
			proTable.find(".subBtn").addClass("disable");
			proTable.find(".storage_td").text("-");
			that.dateInp.val(date);
			date && that.changeciList.query(date);
		});
	},
	//载入场次列表模块
	importChangciList : function(){
		var that = this;
		return new ChangciList().on("changciChange",function(time,area_storage){
			that.changciInp.val(time);
			//场次列表变动时更新产品更表里的库存
			that.product.changeStorage(area_storage);
		});
	},
	//载入产品列表模块
	importProduct : function(){
		var that = this;
		return new Product({container:$("#proTable")});
	},
	onSelectDateInputClick : function(that,e){
		var date = that.dateInp.val();
		that.calendar.show(date);
		queryOTtimeByMonth(date.substring(0,7));
	},
	selectChangciTrigger : function(that,e){
		that.changeciList.show();
	}
});
new Order({container:$("#OrderContainer")})

